﻿namespace IBTrader.Indicator.CandleStick
{
    using IBTrader.Charts;
    using IBTrader.Charts.Drawing;
    using IBTrader.Modules.Read;
    using System;
    using System.Collections.Concurrent;
    using System.Drawing;
    using System.Linq;

    class PivotPoints : Base
    {
        internal enum Type { Standard, Fibonacci, Demark };
        internal new event EventHandler<ChartLines.Item> Hit;
        private readonly Type type;
        public PivotPoints(Worker worker, int interval = 60, Type type = Type.Standard) : base(worker, interval) { this.type = type; }
        protected override void Add(object sender, Item item)
        {
            var point = 0.0;
            double[] bounds = null;
            var HL = item.High - item.Low;
            var HLC = item.High + item.Low + item.Close;
            if (type == Type.Standard)
            {
                point = item.Typical;
                bounds = new[] { point * 2 - item.High, point - HL, point * 2 - item.Low, point + HL };
            }
            else if (type == Type.Fibonacci)
            {
                point = item.Typical;
                bounds = new[] { point - .382f * HL, point - .618f * HL, point - 1f * HL, point + .382f * HL, point + .618f * HL, point + 1f * HL };
            }
            else if (type == Type.Demark)
            {
                if (item.Close > item.Open) point = HLC + item.High;
                if (item.Close < item.Open) point = HLC + item.Low;
                if (item.Close == item.Open) point = HLC + item.Close;
                bounds = new[] { point / 2 - item.High, point / 2 - item.Low };
                point /= 4;
            }
            if (Hit != null)
            {
                var open = item.CloseLine;
                var close = NewLine(open, 0);
                close.DateTime += item.CloseLine.DateTime - item.OpenLine.DateTime;
                Hit(sender, new ChartLines.Item { Lines = new[] { NewLine(open, point), NewLine(close, point) }, Color = Color.Red });
                foreach (var f in bounds)
                    Hit(sender, new ChartLines.Item { Lines = new[] { NewLine(open, f), NewLine(close, f) } });
            }
        }
    }
}